package mephisto.services.impl;

import java.io.StringReader;

import mephisto.Context;
import mephisto.services.IWikiModelService;

import org.wikimodel.wem.IWemListener;
import org.wikimodel.wem.IWikiParser;
import org.wikimodel.wem.IWikiPrinter;
import org.wikimodel.wem.WikiParserException;
import org.wikimodel.wem.common.CommonWikiParser;
import org.wikimodel.wem.xhtml.PrintListener;

public class WikiModelService extends BaseService implements IWikiModelService {

    public WikiModelService() {
        super();
    }

    public String render(String input, Context context) {
        StringReader reader = new StringReader(input);
        IWikiParser parser = newWikiParser();
        final StringBuffer buffer = new StringBuffer();
        IWikiPrinter printer = newPrinter(buffer);
        IWemListener listener = new PrintListener(printer);
        try {
            parser.parse(reader, listener);
        } catch (WikiParserException e) {
            e.printStackTrace();
        }
        String output = buffer.toString();
        output = output.replace("<![CDATA[", "");
        output = output.replace("]]>", "");
        output = output.replace("<pre class='macro' macroName='html'>", "");
        output = output.replace("</pre>", "");

        return output;
    }

    protected IWikiPrinter newPrinter(final StringBuffer buf) {
        IWikiPrinter printer = new IWikiPrinter() {

            public void print(String str) {
                buf.append(str);
            }

            public void println(String str) {
                buf.append(str);
                buf.append("\n");
            }
        };
        return printer;
    }

    protected IWikiParser newWikiParser() {
        return new CommonWikiParser();
    }

}
